package com.xlh.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xlh.common.Result;
import com.xlh.constant.UserConstant;
import com.xlh.entity.UserEntity;
import com.xlh.enums.EventCodeEnum;
import com.xlh.vo.LocalStorageUserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录成功时，自定义的返回结果
 *
 * @author cheer
 */
@Component
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        // 获取用户信息放到结果集中
        LocalStorageUserInfoVO localStorageDTO = getUserInfo();
        // 将验证码放置session中
        HttpSession session = request.getSession(true);
        session.removeAttribute(UserConstant.CODE_SESSION_KEY);
        session.removeAttribute(UserConstant.CODE_FAIL_NUM);
        session.removeAttribute(UserConstant.SMS_CODE_SESSION_KEY);
        session.removeAttribute(UserConstant.MOBILE_TEL_SESSION_KEY);
        session.removeAttribute(UserConstant.SMS_SEND_FAIL_SESSION_KEY);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(objectMapper.writeValueAsString(Result.success(localStorageDTO)));
        response.getWriter().flush();
    }

    private LocalStorageUserInfoVO getUserInfo() {
        // 在结果集中配置用户信息 及 logo等信息，使得前端放到本地缓存中。
        UserEntity user = userInfoHolder.getUser();
        LocalStorageUserInfoVO localStorageDTO = new LocalStorageUserInfoVO();
        localStorageDTO.setName(user.getName());
        localStorageDTO.setRole(user.getRole());
        localStorageDTO.setAccount(user.getAccount());
        localStorageDTO.setIsAdmin(userInfoHolder.isAdmin());
        return localStorageDTO;
    }

}
